// axios基础的封装
import axios from 'axios'
import { useUserStore } from '@/stores'
import { message } from '@/components/ZyMessage/index.js'
import router from '@/router/index.js'

const httpInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  timeout: 5000
})

// axios请求拦截器
httpInstance.interceptors.request.use(
  (config) => {
    // 1. 从pinia获取token数据
    const userStore = useUserStore()
    // 2. 按照后端的要求拼接token数据
    const token = userStore.user.token
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  (error) => Promise.reject(error)
)

// axios响应式拦截器
httpInstance.interceptors.response.use(
  (result) => result.data.data,
  (error) => {
    // token过期处理
    if (error.response?.status === 401) {
      const userStore = useUserStore()
      userStore.logout()
      router.push('/login')
    }
    // 统一错误提示
    const msg = error.response?.data?.data || error.response?.data?.message || '请求失败'
    message(msg, 'error')

    return Promise.reject(error)
  }
)

export default httpInstance
